package org.codingq92.network;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * @author: CodingQ92
 * @date: 2025/6/17 21:49
 */
public class TCPDemo {
    public static void main(String[] args) {
        // 启动TCP Server服务
        new Thread(TCPDemo::server).start();
        // 启动TCP Client服务
        new Thread(TCPDemo::client).start();
    }

    private static void client() {
        try (Socket socket = new Socket("127.0.0.1", 18000); // 连接服务端
             OutputStream outputStream = socket.getOutputStream(); // 获取输出流
             DataOutputStream dos = new DataOutputStream(outputStream)) { // 获取数据输出流
            for (int i = 0; i < 10; i++) {
                dos.writeUTF("hello server_" + i); // 发送数据 一定要和服务端的读取数据方法一致
                System.out.println("发送数据: hello server_" + i);
                Thread.sleep(1000);
            }
//            dos.writeUTF("bye"); // 当前通信结束
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void server() {
        try (ServerSocket serverSocket = new ServerSocket(18000); // 创建服务端
             Socket accept = serverSocket.accept(); // 等待客户端连接 会阻塞！！！
             InputStream inputStream = accept.getInputStream(); // 获取输入流
             DataInputStream dis = new DataInputStream(inputStream)) { // 获取数据输入流
            SocketAddress remoteSocketAddress = accept.getRemoteSocketAddress(); // 获取客户端地址
            while (true) {
                try {
                    String s = dis.readUTF(); // 读取数据 一定要和客户端的发送数据方法一致 会阻塞！！！
//                if ("bye".equals(s)) { // 当前通信结束 跳出循环
//                    break;
//                }
                    System.out.println("来自[" + remoteSocketAddress + "]的数据: " + s);
                } catch (EOFException e) {
                    System.out.println("客户端[" + remoteSocketAddress + "]已经离线!!!");
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
